# jwt_optional_for_options.py
import jwt
from flask import request
from functools import wraps
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
from flask import jsonify

from flaskapp.util.Result import Result
JWT_SECRET_KEY = "your-secret-key"  # 替换为你的密钥
JWT_ALGORITHM = "HS256"

# def jwt_optional_for_options(fn):
#     """
#     自定义装饰器：对OPTIONS请求跳过JWT校验，其它请求执行verify_jwt_in_request()
#     """
#     @wraps(fn)
#     def wrapper(*args, **kwargs):
#         if request.method == 'OPTIONS':
#             # 返回一个 200 空响应即可，表示通过预检
#             return '', 200
#         try:
#             verify_jwt_in_request()
#         except Exception as e:
#             print(f"JWT 验证失败: {str(e)}")
#             return jsonify({
#                 "status": 401,
#                 "msg": "未授权的访问（JWT验证失败）",
#                 "error": str(e)
#             }), 401
#         return fn(*args, **kwargs)
#     return wrapper

# def jwt_required1(f):
#     @wraps(f)
#     def decorated_function(*args, **kwargs):
#         token = request.headers.get('Authorization')
#         if not token:
#             return Result.error(401, "Missing token")
#         try:
#             data = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
#         except jwt.ExpiredSignatureError:
#             return Result.error(401, "Token expired")
#         except jwt.InvalidTokenError:
#             return Result.error(401, "Invalid token")
#         return f(*args, **kwargs)
#     return decorated_function
def jwt_required1(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": "Missing token"
            }), 401
            
        # 解析出令牌部分
        if 'Bearer' in token:
            token = token.split(' ')[1]
            
        try:
            # 尝试解码JWT令牌
            try:
                # 首先尝试标准格式解码
                payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
            except:
                # 如果标准解码失败，尝试解析第三方登录的token格式
                # 这里可能需要根据实际第三方登录的token格式调整
                payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM], options={"verify_signature": False})
            
            # 确保payload中包含必要的字段
            if 'user_id' not in payload:
                # 尝试从sub字段中获取用户信息
                if 'sub' in payload and isinstance(payload['sub'], dict) and 'user_id' in payload['sub']:
                    payload['user_id'] = payload['sub']['user_id']
                    payload['username'] = payload['sub'].get('username', '')
                    payload['is_admin'] = payload['sub'].get('is_admin', False)
            
            request.jwt_payload = payload  # 将解码后的令牌数据存储在请求对象中
            
        except jwt.ExpiredSignatureError:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": "Token expired"
            }), 401
        except jwt.InvalidTokenError as e:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": f"Invalid token: {str(e)}"
            }), 401
        except Exception as e:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": f"Token validation error: {str(e)}"
            }), 401
            
        return f(*args, **kwargs)
    return wrapper

def jwt_optional_for_options(f):
    """
    自定义装饰器：对 OPTIONS 请求跳过 JWT 校验，其它请求执行 JWT 验证
    """
    @wraps(f)
    def wrapper(*args, **kwargs):
        if request.method == 'OPTIONS':
            # 返回一个 200 空响应即可，表示通过预检
            return '', 200
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": "Missing token"
            }), 401
        # 解析出令牌部分
        if 'Bearer' in token:
            token = token.split(' ')[1]
        try:
            payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
            request.jwt_payload = payload  # 将解码后的令牌数据存储在请求对象中
        except Exception as e:
            return jsonify({
                "status": 401,
                "msg": "未授权的访问（JWT 验证失败）",
                "error": str(e)
            }), 401
        return f(*args, **kwargs)
    return wrapper